package com.example.proxy.staticproxy;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;

/**
 * @Description
 * @Date 2021/8/8
 * @Created by Jonathan
 */
@Slf4j
public class LambdaDemo {
    HashMap<String, ObjectFactory<?>> singletonFactories = new HashMap<>();
    String beanName = "testName";
    Object bean = new Stu("zhangsan", 11);

    public Object getEarlyBeanReference(String beanName, Object bean) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("1", beanName);
        map.put("2", bean);
        return map;
    }

    protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
        this.singletonFactories.put(beanName, singletonFactory);
    }

    public void doCreateBean() {
        this.addSingletonFactory(beanName, () -> {
            return getEarlyBeanReference(beanName, bean);
        });
    }

    // 这两个表达式的效果是一样的
    public void doCreateBean1() {
        ObjectFactory<Object> factory = new ObjectFactory<Object>() {
            @Override
            public Object getObject() throws Exception {
                return getEarlyBeanReference(beanName, bean);
            }
        };
        this.addSingletonFactory(beanName,factory);
    }


    protected Object getSingleton(String beanName) throws Exception {
        ObjectFactory<?> singletonFactory = (ObjectFactory) this.singletonFactories.get(beanName);
        Object singletonObject = singletonFactory.getObject();
        return singletonObject;
    }

    public static void main(String[] args) throws Exception {
        LambdaDemo demo = new LambdaDemo();
        //demo.doCreateBean();
        demo.doCreateBean1();
        log.info("ret:{}", demo.getSingleton("testName"));
    }
}
